package main

import (
	"fmt"
	"sync"
)

type SafeDict1 struct {
	data map[string]int
	*sync.Mutex
}

func NewSafeDict1(data map[string]int) *SafeDict1 {
	return &SafeDict1{
		data,
		&sync.Mutex{}, // 一样要初始化,
	}
}

func (d *SafeDict1) Len() int {
	d.Lock()
	defer d.Unlock()
	return len(d.data)
}

func (d *SafeDict1) Put(key string, value int) (int, bool) {
	d.Lock()
	defer d.Unlock()
	old_value, ok := d.data[key]
	d.data[key] = value
	return old_value, ok
}

func (d *SafeDict1) Get(key string) (int, bool) {
	d.Lock()
	defer d.Unlock()
	old_value, ok := d.data[key]
	return old_value, ok
}

func (d *SafeDict1) Delete(key string) (int, bool) {
	d.Lock()
	defer d.Unlock()
	old_value, ok := d.data[key]
	if ok {
		delete(d.data, key)
	}
	return old_value, ok
}

func Write1(d *SafeDict1){
	d.Put("banana",5)
}

func Read1(d *SafeDict1){
	fmt.Println(d.Get("banana"))
}

func main(){
	d := NewSafeDict1(map[string]int{
		"apple":2,
		"melon":3,
	})
	go Read1(d)
	Write1(d)
	fmt.Println(d)
}


